package com.js.rtu.base;


import android.app.Activity;
import android.app.Dialog;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.js.rtu.R;
import com.js.rtu.config.CmdConfig;
import com.js.rtu.custom.DialogHelper;
import com.js.rtu.fragment.third.DebugReadBean;
import com.js.rtu.mvp.bean.Cmd90Bean;
import com.js.rtu.mvp.bean.Cmd92Bean;
import com.js.rtu.mvp.bean.Cmd92Bean_v2_0_1;
import com.js.rtu.mvp.bean.base.CommonBean;
import com.js.rtu.mvp.present.Cmd90Presenter;
import com.js.rtu.mvp.present.Cmd92Presenter;
import com.js.rtu.mvp.present.Cmd92Presenter_v2_0_1;
import com.js.rtu.util.BluetoothUtils;
import com.js.rtu.util.CmdUtils;
import com.js.rtu.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;


public abstract class BaseFragment extends SwipeBackFragment {
    public Activity mActivity;
    protected Unbinder unbinder;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return attachToSwipeBack(view);

    }

    protected abstract int getLayoutId();

    protected abstract void initView();

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mActivity = getActivity();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setParallaxOffset(0.5f);
    }

    protected void initToolbarNav(Toolbar toolbar) {
        toolbar.setNavigationIcon(R.mipmap.ic_arrow_back_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _mActivity.onBackPressed();
            }
        });
    }



    public void toastShow(String resId) {
        ToastUtil.info(resId);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }
        if (unbinder != null) {
            unbinder.unbind();
        }

    }


    private CompositeDisposable mCompositeDisposable;


    public void addSubscription(DisposableObserver observer) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(observer);
    }

    public Dialog loadingDialog;

    public Dialog showLoadingDialog() {
        if (loadingDialog == null)
            loadingDialog = new DialogHelper().getLoading(_mActivity, "加载中");
        if (!loadingDialog.isShowing())
            loadingDialog.show();
        return loadingDialog;
    }


    public Dialog showLoadingDialog(String message) {
        if (loadingDialog == null)
            loadingDialog = new DialogHelper().getLoading(_mActivity, message);
        if (!loadingDialog.isShowing())
            loadingDialog.show();
        return loadingDialog;
    }


    public void dismissLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            // progressDialog.hide();会导致android.view.WindowLeaked
            loadingDialog.dismiss();
        }
    }

    protected void initRecyclerView(RecyclerView rcyList, BaseQuickAdapter mAdapter, int spanCount) {
        GridLayoutManager mGridLayoutManager = new GridLayoutManager(_mActivity, spanCount);
        //方向，水平
        mGridLayoutManager.setOrientation(RecyclerView.VERTICAL);
        //给RecyclerView设置布局管理器
        rcyList.setLayoutManager(mGridLayoutManager);
        rcyList.setHasFixedSize(true);
        rcyList.setLayoutManager(mGridLayoutManager);
        rcyList.setAdapter(mAdapter);
        mAdapter.openLoadAnimation();
    }


    public void get92Info() {
        String cmd = CmdUtils.getCmd(CmdConfig.CMD_92);
        BluetoothUtils.send(cmd, new BluetoothUtils.onCallback() {
            @Override
            public void onReceive(String msg) {
                EventBus.getDefault().post(new DebugReadBean(msg));
//                Cmd92Presenter presenter = new Cmd92Presenter();
//                CommonBean<Cmd92Bean> bean = presenter.paseData(msg);
//                presenter.setInfo(bean);
//                dismissLoadingDialog();

                Cmd92Presenter_v2_0_1 presenter = new Cmd92Presenter_v2_0_1();
                CommonBean<Cmd92Bean_v2_0_1> bean = presenter.paseData(msg);
                presenter.setInfo(bean);
                dismissLoadingDialog();

            }

            @Override
            public void onFail(String err) {
                dismissLoadingDialog();
                toastShow(err);
            }
        });
    }


    public void get90Info() {
        String cmd = CmdUtils.getCmd(CmdConfig.CMD_90);
        BluetoothUtils.send(cmd, new BluetoothUtils.onCallback() {
            @Override
            public void onReceive(String msg) {
                EventBus.getDefault().post(new DebugReadBean(msg));
                Cmd90Presenter presenter = new Cmd90Presenter();
                CommonBean<Cmd90Bean> bean = presenter.paseData(msg);
                presenter.setInfo(bean);
                dismissLoadingDialog();
            }

            @Override
            public void onFail(String err) {
                dismissLoadingDialog();
                toastShow(err);
            }
        });
    }


    public void add(String str, LinearLayout llDebug) {
        if (llDebug == null)
            return;
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                emitter.onNext(str);
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String pS) {
                        TextView time = new TextView(_mActivity);
                        time.setTextSize(14);
                        time.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                        time.setTextIsSelectable(true);
                        TextView tv = new TextView(_mActivity);
                        tv.setTextSize(12);
                        tv.setTextIsSelectable(true);
                        tv.setBackground(null);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                        String dateNowStr = sdf.format(new Date());

                        time.setText(dateNowStr);
                        tv.setText(String.format("%s", pS));
                        llDebug.addView(tv, 0);
                        llDebug.addView(time, 0);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }



}
